package com.yf.yfwebview.web

import android.annotation.SuppressLint
import android.content.Context
import android.text.TextUtils
import android.util.AttributeSet
import android.webkit.JavascriptInterface
import android.webkit.WebView
import com.google.gson.Gson
import com.yf.yfwebview.JsParam
import com.yf.yfwebview.WebViewCommandDispatcher

class YFWebView @JvmOverloads constructor(context: Context, attributeSet: AttributeSet? = null, defaultStyle: Int = 0) :
    WebView(context, attributeSet, defaultStyle) {
    init {
          WebViewCommandDispatcher.initAidl()
          addJavascriptInterface(this,"yfwebview")
          WebViewDefaultSettings.getInstance().setSettings(this)
    }
    @SuppressLint("JavascriptInterface")
    fun registerWebViewCallBack(callBack: WebViewCallBack){
        webViewClient = YFWebViewClient(callBack)
        webChromeClient = WebViewChromeClient(callBack)

    }
    @JavascriptInterface
    fun takeNativeAction(json:String){
         if (!TextUtils.isEmpty(json)){
             val fromJson = Gson().fromJson(json, JsParam::class.java)
             if (fromJson!=null){
                // Toast.makeText(context, "${fromJson.name}----${fromJson.param}", Toast.LENGTH_SHORT).show()
                 WebViewCommandDispatcher.handleCommand(fromJson.name,fromJson.param.toString())
             }
         }
    }
    fun handleCallback(callbackname: String, response: String) {
        if (!TextUtils.isEmpty(callbackname) && !TextUtils.isEmpty(response)) {
            post {
                val jscode = "javascript:yfjs.callback('$callbackname',$response)"
                evaluateJavascript(jscode, null)
            }
        }

    }
}